<?php
Yii::import('dao.bid.BidDao');
class Invited  extends CFormModel{
    const  INVITE_GENERATE='GENERATE';
    const  INVITE_SUCCESS='SUCCESS';
    const  INVITE_SUCCESS_BONUS=5;
    
    public $customerId;
    public $cookie;
    public $refer;
    protected $_bidDao;
    public $url;
    
    public function init(){
        $this->_bidDao=new BidDao();
    }
    
    public function rules(){
        return array(
            array('refer','withRefer','on'=>'visit'),
            array('refer','validRefer','on'=>'visit'),
            array('refer','hasCookie','on'=>'register'),
        );
    }
    
    public function validRefer($attribute,$params){
         $refer=new CustomerInfo();
         $refer=$refer->findByAttributes(array('refer'=>$this->refer));
         if (empty($refer)){
             $this->addError($attribute, 'This refer is not valid!');
         }
    }
    
    public function hasCookie($attribute,$params){
            $cookie=$this->getCookie();
            if($cookie===null){
                $this->addError($attribute, 'cookie is not find!');
            }
    }
    
    public function withRefer($attribute,$params){
         switch (true){
             case !empty($_GET['ref']):
                 break;
             case !empty(Yii::app()->request->cookies['refer']):
                 break;
             default:
                 $this->addError($attribute, 'Without refer!');
         }
    }
    
    public function getCookie($name='refer'){
            $cookie=Yii::app()->request->cookies[$name];
            $cookieValue=null;
            if (!empty($cookie)){
                $cookieValue=$cookie->value;
            }
            return $cookieValue;
    }
    
    public function setCookie($name,$value,$expire=null){
        if ($expire===null){
            $expire=time()+86400;
        }
        $cookie=new CHttpCookie($name, $value);
        $cookie->expire=$expire;
        return Yii::app()->request->cookies[$name]=$cookie;
    }
    
    public function getRef(){
        $customerInfo=new CustomerInfo();
        $customerInfo=$customerInfo->findByAttributes(array('customer_id'=>$this->customerId));
        if (!empty($customerInfo)){
            $this->refer=$customerInfo->refer;
        }
    }
    
    public function generateUrl(){
           $url='http://pa.egunner.com?ref='.$this->refer;           
           return $this->url=$url;
    }
}